package com.announcement.controller;

import java.io.File;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.announcement.entity.User;
import com.announcement.sevice.UserService;

@RequestMapping("/user")
@Controller
public class FileUploadController implements ServletContextAware {

	private ServletContext servletContext;
	@Autowired
	private UserService userService;

	public void setServletContext(ServletContext context) {
		this.servletContext = context;
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String handleUploadData(String name,
			@RequestParam("file") CommonsMultipartFile file,
			HttpServletRequest req) {
		if (!file.isEmpty()) {
			String path = this.servletContext.getRealPath("/upload/");
			System.out.println(path);
			String fileName = file.getOriginalFilename();
			String fileType = fileName.substring(fileName.lastIndexOf("."));
			System.out.println(fileType);
			String userlogo = new Date().getTime() + fileType;

			File file2 = new File(path, userlogo);
			try {
				file.getFileItem().write(file2);
			} catch (Exception e) {
				e.printStackTrace();
			}
			User user = (User) req.getSession().getAttribute("OnlineUser");
			if (user == null)
				return null;

			System.out.println(user.getUserId());
			user.setUserlogo("http://localhost:8080/Announcement/upload/"
					+ userlogo);
			System.out.println(user.getUserlogo());
			boolean status = userService.updateUser(user);
			if (status)
				return "redirect:/message/showArticleToHome?pageIndex=1";
			return "uploadface";
		} else {
			return "uploadface";
		}
	}
}
